package cn.edu.zjicm.wordsnet_d.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.drawable.ColorDrawable;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentTransaction;
import android.util.TypedValue;
import android.view.Display;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;
import cn.edu.zjicm.wordsnet_d.R;
import cn.edu.zjicm.wordsnet_d.activity.base.WordBaseActivity;
import cn.edu.zjicm.wordsnet_d.data.OneWord;
import cn.edu.zjicm.wordsnet_d.data.test.Question;
import cn.edu.zjicm.wordsnet_d.data.test.ReviewManager;
import cn.edu.zjicm.wordsnet_d.data.test.TestActivityInterface;
import cn.edu.zjicm.wordsnet_d.datapersistent.FileManager;
import cn.edu.zjicm.wordsnet_d.db.WordFactory;
import cn.edu.zjicm.wordsnet_d.download.DownloadManager;
import cn.edu.zjicm.wordsnet_d.fragment.ExamRunMode2Fragment;
import cn.edu.zjicm.wordsnet_d.util.NightModeUtil;
import cn.edu.zjicm.wordsnet_d.view.WriteView;

import com.umeng.analytics.MobclickAgent;

public class ExamReviewActivity extends WordBaseActivity implements Runnable, TestActivityInterface {
	public static void startActivity(Context context, int familiarDegree) {
		Intent i = new Intent(context, ExamReviewActivity.class);
		i.putExtra("familiar_degree", familiarDegree);
		context.startActivity(i);
	}

	private PopupWindow mWriteWindow;
	private WriteView mWriteView;
	private ViewFlipper mainFlipper;
	public TextView testResultText1Front;
	public TextView testResultText1;
	public ProgressBar mProgressBar1;

	public TextView writeAgainButton_independent, closeButton_independent;

	private LinearLayout mScrollView;

	private View mMask; // 弹出窗口时的遮罩

	private int familiarDegree;

	WordFactory wf = WordFactory.getInstance(this);

	private ReviewManager testManager; // 全部测试题
	private Question rQuestion; // 当前测试题

	private PopupWindow mPopupWindow;
	private View menuView;
	private int screenWidth;
	Display display;

	Handler handler = new Handler();
	ExamRunMode2Fragment mMode2Fragment = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// 设定调整音量为媒体音量
		setVolumeControlStream(AudioManager.STREAM_MUSIC);

		// setTitleTextGravityCenter();
		setBackButton(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				stopTest();
			}
		});

		familiarDegree = this.getIntent().getIntExtra("familiar_degree", -1);

		initTitle();

		setContentView(R.layout.activity_exam_review);

		mainFlipper = (ViewFlipper) findViewById(R.id.main_flipper);
		testResultText1Front = (TextView) findViewById(R.id.test_result_text1_front);
		testResultText1 = (TextView) findViewById(R.id.test_result_text1);
		mProgressBar1 = (ProgressBar) findViewById(R.id.progressBar1);

		mMask = (LinearLayout) findViewById(R.id.exam_run_fake_scroll_view);
		mScrollView = (LinearLayout) findViewById(R.id.exam_run_scroll_view);

		startTest();
		initTestCount();
		displayResult();
	}

	void initTitle() {
		setTitleBarStyle(TITLE_BAR_STYLE_BACK_BUTTON);
		setTitleText("词义回想");

		if (familiarDegree == OneWord.DEGREE_FAMILIAR) {
			initMenu(getRightButton1());
			setRightButton1(null, R.drawable.more_button_selector, new OnClickListener() {
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					mPopupWindow.showAsDropDown(getRightButton1(), -(int) (mPopupWindow.getWidth() - 9.0 * getRightButton1().getWidth() / 10.0), 0);
				}
			});
		}
	}

	@SuppressLint("NewApi")
	private void initMenu(View view) {
		display = getWindowManager().getDefaultDisplay();
		// android3.2以前获取屏幕宽度用display.getWidth()取得，android3.2以后Google推荐用getSize()方法获得。
		if (android.os.Build.VERSION.SDK_INT >= 13) {
			Point size = new Point();
			display.getSize(size);
			screenWidth = size.x;
		} else {
			screenWidth = display.getWidth();
		}

		LayoutInflater mLayoutInflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
		menuView = mLayoutInflater.inflate(R.layout.popmenu_exam_review, null);
		mPopupWindow = new PopupWindow(menuView, (int) (screenWidth / 2.0), ViewGroup.LayoutParams.WRAP_CONTENT);
		mPopupWindow.setFocusable(true); // 取得焦点，创建出来的popupWindow默认无焦点
		mPopupWindow.setTouchable(true);
		mPopupWindow.setOutsideTouchable(true);
		ColorDrawable mDrawable = new ColorDrawable(00000000);
		mPopupWindow.setBackgroundDrawable(mDrawable);
		mPopupWindow.update();
		menuView.setFocusableInTouchMode(true);
		menuView.setOnKeyListener(new OnKeyListener() {
			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				if ((keyCode == KeyEvent.KEYCODE_MENU) && (mPopupWindow.isShowing())) {
					mPopupWindow.dismiss();// 这里写明模拟menu的PopupWindow退出就行
					return true;
				}
				return false;
			}
		});

		LinearLayout setToTooeasyButton = (LinearLayout) menuView.findViewById(R.id.btn_set_to_tooeasy);
		setToTooeasyButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				testManager.setTooTooEasy(rQuestion);
				handler.postDelayed(ExamReviewActivity.this, TEST_INTERVAL);
				mPopupWindow.dismiss();
			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add("menu");
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onMenuOpened(int featureId, Menu menu) {
		if (familiarDegree == OneWord.DEGREE_FAMILIAR) {
			if (!mPopupWindow.isShowing()) {
				mPopupWindow.showAsDropDown(getRightButton1(), -(int) (mPopupWindow.getWidth() - 9.0 * getRightButton1().getWidth() / 10.0), 0);
			} else {
				mPopupWindow.dismiss();
			}
		}
		return false;
	}

	void startTest() {
		mainFlipper.setDisplayedChild(0);

		testManager = new ReviewManager(this, familiarDegree);

		nextQuestion();
	}

	private void nextQuestion() {
		// TODO Auto-generated method stub
		handler.removeCallbacks(this);

		rQuestion = testManager.nextQuestion();
		if (rQuestion != null) {
			mode1();
		} else {
			stopTest();
		}
	}

	// 结束测试，进入TestEndActivity
	private void stopTest() {
		finish();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		boolean consumed = false;
		switch (keyCode) {
		case KeyEvent.KEYCODE_BACK:
			stopTest();
		}
		return consumed;
	}

	public void showDownloadVoiceWindow(Handler handler) {
		mMask.setBackgroundColor(Color.parseColor("#66000000"));
		DownloadManager downloadManager = new DownloadManager(this, handler, true, rQuestion.getWord());
		downloadManager.showAskDownloadWindow();
	}

	public void displayWriteView() {
		mainFlipper.setDisplayedChild(1);

		TypedValue typedValue = new TypedValue();
		getTheme().resolveAttribute(R.attr.spell_dialog_bg_blur, typedValue, true);
		mMask.setBackgroundResource(typedValue.resourceId);
		mMask.scrollTo(0, mScrollView.getScrollY());
		hideTitle();
	}

	ImageView playVoice = null;

	public void showWriteWindow() {
		if (mWriteWindow == null) {
			// init PopWindow cotentview
			View view = View.inflate(this, R.layout.window_write, null);
			ImageView writeAgainButton = (ImageView) view.findViewById(R.id.write_again_button);
			ImageView hintButton = (ImageView) view.findViewById(R.id.hint);
			ImageView closeButton = (ImageView) view.findViewById(R.id.write_close_button);
			playVoice = (ImageView) view.findViewById(R.id.play_voice_writeview);
			mWriteView = (WriteView) view.findViewById(R.id.write_view);

			writeAgainButton.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					mWriteView.reWrite();
				}
			});
			closeButton.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					mWriteWindow.dismiss();
				}
			});
			hintButton.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					Toast.makeText(ExamReviewActivity.this, mWriteView.hint(), Toast.LENGTH_SHORT).show();
				}
			});
			playVoice.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					mWriteView.playOneWordVoice();
				}
			});
			mWriteWindow = new PopupWindow(view, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
			mWriteWindow.setFocusable(true);
			mWriteWindow.setBackgroundDrawable(getResources().getDrawable(R.drawable.transparent_bg_drawable));
			mWriteWindow.setOnDismissListener(new OnDismissListener() {
				@Override
				public void onDismiss() {
					displayDetailView();
					showTitle();
				}
			});
		}
		// mWriteView.init(rQuestion.getLemma(), rQuestion.getCn(),
		// rQuestion.getPhonetic());

		if (playVoice != null) {
			if (NightModeUtil.isNightModeNow()) {
				if (FileManager.isVoiceFileExist(ExamReviewActivity.this, rQuestion.getWord())) {
					playVoice.setImageResource(R.drawable.write_view_play_voice_ico_night_selector);
				} else {
					playVoice.setImageResource(R.drawable.write_view_play_ico_unclickable_night);
				}
			} else {
				if (FileManager.isVoiceFileExist(ExamReviewActivity.this, rQuestion.getWord())) {
					playVoice.setImageResource(R.drawable.write_view_play_voice_ico_selector);
				} else {
					playVoice.setImageResource(R.drawable.write_view_play_ico_unclickable);
				}
			}
		}

		mWriteView.init(rQuestion.getWord());
		mWriteView.reWrite();
		if (mWriteView.isToShowKeyBoard()) {
			mWriteWindow.showAtLocation(mMask, Gravity.TOP, 0, 0);
		} else
			mWriteWindow.showAtLocation(mMask, Gravity.CENTER, 0, 0);
	}

	public void displayDetailView() {
		// this.setTitleText(currentWord.getLemma());
		mainFlipper.setDisplayedChild(0);
	}

	public void next(boolean result) {
		// TODO Auto-generated method stub
		if (result)
			testManager.rightAnswer(rQuestion);
		else
			testManager.wrongAnswer(rQuestion);
		handler.postDelayed(ExamReviewActivity.this, TEST_INTERVAL);
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		this.nextQuestion();
	}

	public static final int TEST_INTERVAL = 0;

	void mode1() {
		if (mMode2Fragment == null) {
			mMode2Fragment = new ExamRunMode2Fragment(rQuestion.getWord(), this);
			FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
			ft.add(R.id.word_exam_mode2_fragment_container, mMode2Fragment);
			ft.commit();
		} else
			mMode2Fragment.initViewForNewWord(rQuestion.getWord());
	}

	int newWordNumber, newWordCount;

	void initTestCount() {
		newWordNumber = testManager.size();
		newWordCount = 0;
	}

	void displayResult() {
		testResultText1Front.setText("复习单词");
		testResultText1.setText(newWordCount + "/" + newWordNumber);

		if (newWordNumber == 0)
			mProgressBar1.setProgress(100);
		else
			mProgressBar1.setProgress(100 * newWordCount / newWordNumber);
	}

	public void updateResult() {
		newWordCount++;
		displayResult();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		MobclickAgent.onResume(this);
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		MobclickAgent.onPause(this);
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}

	@Override
	public void removeCurWord() {
		// TODO Auto-generated method stub

	}

	@Override
	public void next(ANSWER_RESULT result) {
		if (result == TestActivityInterface.ANSWER_RESULT.RIGHT)
			testManager.rightAnswer(rQuestion);
		else
			testManager.wrongAnswer(rQuestion);
		handler.postDelayed(ExamReviewActivity.this, TEST_INTERVAL);
	}
}
